package org.qpcr.community.project.web;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hswebframework.web.authorization.annotation.Authorize;
import org.hswebframework.web.authorization.annotation.QueryAction;
import org.hswebframework.web.authorization.annotation.Resource;
import org.hswebframework.web.crud.web.reactive.ReactiveServiceCrudController;
import org.qpcr.community.project.model.entity.DataAnalysisExperimentalRecordsEntity;
import org.qpcr.community.project.model.entity.ExperimentalRecordsInstanceEntity;
import org.qpcr.community.project.model.entity.excel.DataAnalysisExcelDataResponse;
import org.qpcr.community.project.model.entity.excel.ExcelDataResponse;
import org.qpcr.community.project.service.DataAnalysisExperimentalRecordsService;
import org.springframework.http.MediaType;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.util.Collection;

@RestController
@RequestMapping({"/project/data-analysis-experimental-records", "/project/data-analysis-experimental/records"})
@Authorize(ignore = true)
@Resource(id = "data-analysis-experimental-records-instance", name = "实验记录")
@Slf4j
@Tag(name = "实验记录接口")
@RequiredArgsConstructor
public class DataAnalysisExperimentalRecordsController  implements
    ReactiveServiceCrudController<DataAnalysisExperimentalRecordsEntity, String> {
    @Getter
    private final DataAnalysisExperimentalRecordsService service;


    /**
     * 批量保存实验记录
     */
    @PostMapping("/batch")
    @QueryAction
    @Authorize(ignore = true)
    public Mono<Integer> saveBatch(@RequestBody Collection<DataAnalysisExperimentalRecordsEntity> entities) {
        return service.saveBatch(entities);
    }

    @PostMapping(value = "/parsing-excel", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Authorize(ignore = true)
    @Operation(summary = "上传实验数据Excel文件")
    public Mono<DataAnalysisExcelDataResponse> parsingExcel(@RequestPart("file") FilePart filePart, String dataId, String groupId, String source) {
        return service.parseExcelToExperimentalRecords(filePart,dataId,groupId,source)
                           .doOnSuccess(entity -> log.info("成功解析Excel文件，生成实验记录实体: {}", entity.getData().getId()))
                           .doOnError(error -> log.error("解析Excel文件失败", error));
    }

    /**
     * 测试解析实验信息
     */
    @GetMapping("/test-parse")
    @Authorize(ignore = true)
    @Operation(summary = "测试解析实验信息")
    public Mono<String> testParseExperimentalInfo() {
        service.testParseExperimentalInfo();
        return Mono.just("测试完成，请查看日志输出");
    }


}
